<?php
/**
 * created by zzy
 * date: 2017/11/30 16:48
 */
namespace App\Api\Service\Forms\Controllers;

use App\Eloquent\Ygt\Product;
use Framework\BaseClass\Api\Controller;
use App\Eloquent\Ygt\DepartmentUser;
use App\Eloquent\Ygt\OrderMaterialCourse;
use App\Eloquent\Ygt\Process;
use App\Engine\Func;
use DB;

class ScrapController extends Controller
{
    public function index()
    {
        $userId                = Func::getHeaderValueByName( 'userid' );
        $info                   = DepartmentUser::getCurrentInfo( $userId );

        $pageSize               = request( 'pageSize', 10 );
        $page                   = request( 'page', 1 );
        $offset                 = ( $page - 1 ) * $pageSize;
        $processType           = request( 'process_id', '' );
        $startDate             = request( 'start_date', '' );
        $endDate               = request( 'end_date', '' );

        if( !$info ){
            xThrow( 10006 );
        }
        $startTime             = Func::getFormsDateTime( $startDate );
        $endTime               = Func::getFormsDateTime( $endDate, true );
        $companyId             = $info->company_id;

        //取废料总价列表
        $sum                = DB::raw('SUM(a.scrap_price) AS scrap_price_sum');
        $query              = DB::table('ygt_order_material_course as a');
        $query              = $query->select( 'material_id',$sum );
        $query              = $query->leftJoin('ygt_product as b', 'b.id', '=', 'a.material_id');
        $query              = $query->where('a.company_id','=', $companyId);
        if( $processType != '' )
        {
            $query              = $query->where('a.process_type','=', $processType);
        }
        $query              = $query->where('a.created_at', '>', $startTime);
        $query              = $query->where('a.created_at', '<', $endTime);
        $query              = $query->groupBy('a.material_id');
        $query              = $query->orderBy('scrap_price_sum','desc');
        $query              = $query->limit($pageSize);
        $query              = $query->offset($offset);
        $listCollection    = $query->get();
        $listsArr          = $listCollection->toArray();
        //列表转换
        $lists              = [];
        $productIdArr     = [];
        $scrapMoney        = 0;
        foreach( $listsArr as $key=>$val )
        {
            $valScrapPriceSum    = $val->scrap_price_sum;
            $valMaterialId        = $val->material_id;
            $productIdArr[]       = $valMaterialId;
            $arr                    = [
                'product_id'=>$valMaterialId, 'scrap_price_sum'=>$valScrapPriceSum,
            ];
            $lists[]                = $arr;
            $scrapMoney            += $valScrapPriceSum;
        }
        //损耗金额最高的材料
        $sum                = DB::raw('SUM(a.scrap_price) AS scrap_price_sum');
        $query              = DB::table('ygt_order_material_course as a');
        $query              = $query->select( 'material_id',$sum );
        $query              = $query->leftJoin('ygt_product as b', 'b.id', '=', 'a.material_id');
        $query              = $query->where('a.company_id','=', $companyId);
        if( $processType != '' )
        {
            $query              = $query->where('a.process_type','=', $processType);
        }
        $query              = $query->where('a.created_at', '>', $startTime);
        $query              = $query->where('a.created_at', '<', $endTime);
        $query              = $query->groupBy('a.material_id');
        $query              = $query->orderBy('scrap_price_sum','desc');
        $query              = $query->limit($pageSize);
        $query              = $query->offset($offset);
        $maxCollection     = $query->first();
        $maxScrapPriceSum            = 1;
        if( $maxCollection )
        {
            $maxScrapPriceSum        = $maxCollection->scrap_price_sum;
        }
        //当前分页的材料名称
        if( $productIdArr )
        {
            $where                      = ['id'=>['in',$productIdArr]];
            $query                      = DB::table('ygt_product');
            $query                      = $query->select( 'id','product_name' );
            $query                      = $query->whereIn('id', $productIdArr);
            $productListCollection    = $query->get();
            $productArr                = $productListCollection->pluck('product_name', 'id')->toArray();
            //var_dump($productArr);exit;
            foreach ($lists as $key=>$val)
            {
                $valProductId         = $val['product_id'];
                $valScrapPriceSum    = $val['scrap_price_sum'];

                $title                  = '该材料已删除';
                if( isset($productArr[$valProductId]) )
                {
                    $title              = $productArr[$valProductId];
                }
                $lists[$key]['title']  = $title;

                $percent                = 0;
                if($maxScrapPriceSum>0)
                {
                    $percentNum            = ($valScrapPriceSum/$maxScrapPriceSum)*100;
                    $percentRound          = round( $percentNum );
                    $percent                = $percentRound/100;
                }
                $lists[$key]['percent']= $percent;
            }
        }
        //取总单数
        $query              = DB::table('ygt_order_material_course');
        $query              = $query->where('company_id','=', $companyId);
        if( $processType != '' )
        {
            $query              = $query->where('process_type','=', $processType);
        }
        $query              = $query->where('created_at', '>', $startTime);
        $query              = $query->where('created_at', '<', $endTime);
        $count              = $query->count();
        //取工单中用的材料总数
        $query              = DB::table('ygt_order_material_course');
        $query              = $query->select( 'material_id' );
        $query              = $query->where('company_id','=', $companyId);
        if( $processType != '' )
        {
            $query              = $query->where('process_type','=', $processType);
        }
        $query              = $query->where('created_at', '>', $startTime);
        $query              = $query->where('created_at', '<', $endTime);
        $query              = $query->groupBy('material_id');
        $productCount      = $query->get()->count();
        //取废料数量列表
        $sum                = DB::raw('SUM(scrap_number) AS scrap_number_sum');
        $query              = DB::table('ygt_order_material_course');
        $query              = $query->select( 'material_id',$sum );
        $query              = $query->where('company_id','=', $companyId);
        if( $processType != '' )
        {
            $query              = $query->where('process_type','=', $processType);
        }
        $query              = $query->where('created_at', '>', $startTime);
        $query              = $query->where('created_at', '<', $endTime);
        $query              = $query->where('scrap_number', '!=', null);
        $query              = $query->groupBy('material_id');
        $query              = $query->orderBy('scrap_number_sum','desc');
        $scrapNumberCollection    = $query->get();
        $scrapNumberArr           = $scrapNumberCollection->pluck('scrap_number_sum', 'material_id')->toArray();
        //取领取数量列表
        $sum                = DB::raw('SUM(receive_number) AS receive_number_sum');
        $query              = DB::table('ygt_order_material_course');
        $query              = $query->select( 'material_id',$sum );
        $query              = $query->where('company_id','=', $companyId);
        if( $processType != '' )
        {
            $query              = $query->where('process_type','=', $processType);
        }
        $query              = $query->where('created_at', '>', $startTime);
        $query              = $query->where('created_at', '<', $endTime);
        $query              = $query->where('receive_number', '>', 0);
        $query              = $query->groupBy('material_id');
        $query              = $query->orderBy('receive_number_sum','desc');
        $receiveNumberCollection  = $query->get();
        $receiveNumberArr         = $receiveNumberCollection->pluck('receive_number_sum', 'material_id')->toArray();
        $percentPercent            = $percent_percent_number = 0;
        foreach ($scrapNumberArr as $key=>$val)
        {
            $valProductId          = $key;
            $percent                 = 0;
            if( isset( $scrapNumberArr[$valProductId] ) && isset( $receiveNumberArr[$valProductId] ) )
            {
                $scrap_number           = $scrapNumberArr[$valProductId];
                $receive_number         = $receiveNumberArr[$valProductId];
                $percentNum            = ($scrap_number/$receive_number)*100;
                $percentRound          = round( $percentNum );
                $percent                = $percentRound/100;
            }
            $percentPercent            += $percent;
            $percent_percent_number     += 1;
        }
        $percentTotal          = 0;
        if( $percent_percent_number > 0 )
        {
            $percentTotal      = ($percentPercent/$percent_percent_number)*100;
            $percentTotal      = round( $percentTotal );
            $percentTotal      = $percentTotal/100;
        }
        $data               = [
            'lists'=>$lists, 'count'=>$count, 'percent_total'=>$percentTotal, 'scrap_money'=>$scrapMoney
        ];
        $pagingData         = [
            'page'         => $page,
            'pageSize'     => $pageSize,
            'total'        => $productCount,
            'keyword'       => ''
        ];
        return $this->pagingData($data, $pagingData);
    }
    public function lists()
    {
        $userId                = Func::getHeaderValueByName( 'userid', 1 );
        $info                   = DepartmentUser::getCurrentInfo( $userId );

        $pageSize               = request( 'pageSize', 10 );
        $page                   = request( 'page', 1 );
        $offset                 = ( $page - 1 ) * $pageSize;
        if( !$info ){
            xThrow( 10006 );
        }
        $companyId             = $info->company_id;
        //取列表
        $query                  = DB::table('ygt_order_material_course as a');
        $query                  = $query->select( 'a.id','e.order_title','e.created_at','e.finished_date','f.title' );
        $query                  = $query->leftJoin('ygt_product as b', 'b.id', '=', 'a.material_id');
        $query                  = $query->leftJoin('ygt_order_process_course as c', 'c.id', '=', 'a.order_process_course_id');
        $query                  = $query->leftJoin('ygt_order_process as d', 'd.id', '=', 'c.order_process_id');
        $query                  = $query->leftJoin('ygt_order as e', 'e.id', '=', 'd.order_id');
        $query                  = $query->leftJoin('ygt_order_type as f', 'f.id', '=', 'e.order_type');
        $query                  = $query->where('a.company_id','=', $companyId);
        $query                  = $query->orderBy('id','desc');
        $query                  = $query->limit($pageSize);
        $query                  = $query->offset($offset);
        $lists_collection       = $query->get();
        $listsArr              = $lists_collection->toArray();
        //取总数
        $query                  = DB::table('ygt_order_material_course as a');
        $count                  = $query->count();
        $lists                  = [];
        foreach( $listsArr as $key=>$val)
        {
            $valId             = $val->id;
            $valOrderTitle    = $val->order_title;
            $valFinishedDate  = $val->finished_date;
            $valTitle          = $val->title;
            $valCreatedAt     = $val->created_at;
            $created_atYmd     = date('Y-m-d',$valCreatedAt);
            $arr                = [
                'id'=>$valId,'order_title'=>$valOrderTitle,
                'finished_date'=>$valFinishedDate,'title'=>$valTitle,
                'created_at'=>$valCreatedAt,'created_at_ymd'=>$created_atYmd
            ];
            $lists[]            = $arr;
            //print_r($arr);echo '<hr/>';
        }
        $pagingData         = [
            'page'         => $page,
            'pageSize'     => $pageSize,
            'total'        => $count,
            'keyword'       => ''
        ];
        return $this->pagingData($lists, $pagingData);
    }
    public function process()
    {
        $userId                = Func::getHeaderValueByName( 'userid', 1 );
        $info                   = DepartmentUser::getCurrentInfo( $userId );

        if( !$info ){
            xThrow( 10006 );
        }
        $companyId             = $info->company_id;
        $where                  = ['is_last'=>1,'company_id'=>$companyId];
        $lists                  = Process::getList($where,'id,title')->toArray();
        return $lists;
    }
}
